<?php

namespace App\Http\Controllers;

use App\Http\Requests\CreateProjectRequest;
use App\Http\Requests\UpdateProjectRequest;
use App\Project;
use App\Repositories\ProjectsRepository;
use Illuminate\Http\Request;

class ProjectsController extends Controller
{
    protected $repo;
    public function __construct(ProjectsRepository $repo)
    {
        $this->repo = $repo;   // ($this->repo是这个类自定义的protected $repo;)
        // ($repo是传进来的(ProjectsRepository $repo),以后再调用可以使用$this->repo来获取传进来的$repo)
        $this->middleware('auth');
    }

    //
    public function index()
    {
        // 查询当前用户创建的所有项目
        $projects = request()->user()->projects()->get();
        // 将查询结果赋值给前端HTML页面
        return view('welcome', compact('projects'));
    }

    public function store(CreateProjectRequest $request){

        $this->repo->create($request);
        // 创建成功之后返回首页
        return back();
    }

    //
    public function show($id){
        $project = Project::findOrFail($id);
        return view('projects.show', compact('project'));
    }

    // 当成Project表的实例$project来接收
    public function destroy(Project $project){
        // 框架会自动去Projects表里删除对应id的那一条数据(实例)
        $project->delete();
        return back();
    }

    // 更新
    public function update(UpdateProjectRequest $request, $id){
        $project = Project::findOrFail($id);
        $project->name = $request->name;
        if($request->hasFile('thumbnail')) {
            // 存储原始图片
            $thumb = $request->thumbnail;
            $name = $thumb->hashName();
            $thumb->storeAs('public/thumbs/original', $name);
            $project->thumbnail = $name;
        }
        $project->save();
        return back();
    }



}
